package form
{
   import flash.events.*;
   import flash.display.*;
   import flash.net.*;
   import flash.text.*;
   import flash.utils.*;
   import flash.ui.*;
   // fl
   import fl.controls.*;
   import fl.managers.*;
   // adobe
   import com.adobe.images.JPGEncoder;
   // casa
   import org.casalib.util.StringUtil;
   // prj
   import boy.contrib.net.Base64;
   import boy.contrib.net.URLRequestBuilder;

   /**
    * 上傳表單資料和圖片範例
    * @author  cjboy1984@gmail.com
    * @usage
    */
   public class UsrForm extends MovieClip
   {
      // fla
      public var tfName:TextField;
      public var tfTel:TextField;
      public var tfAddr:TextField;
      public var tfEmail:TextField;
      public var tfID:TextField;

      // ------------------ LINE -------------------

      // 上傳的程式頁面
      private const POST_URL:String = 'save.php';

      // 為了tab順序、自動換行的功能而存在
      private var textFields:Array;

      // 傳送資料用
      private var ldr:URLLoader;
      public var canSend:Boolean = false;

      /// constructor
      public function UsrForm()
      {
         stop();

         // disable yellow rect
         focusRect = false;

         addEventListener(Event.ADDED_TO_STAGE, onAdd);
         addEventListener(Event.REMOVED_FROM_STAGE, onRemove);
      }

      // ------------------ LINE -------------------

      // 一定要先呼叫！流程是 check() -> sendData()
      public function check():Boolean
      {
         var ret:Boolean = false;
         // check
         if (getName().length == 0)
         {
            MyAlert.jsShow('請填寫您的大名哦！');
         }
         else if (getTel().length == 0)
         {
            MyAlert.jsShow('請填寫您的聯絡電話哦！');
         }
         else if (getAddr().length == 0)
         {
            MyAlert.jsShow('請填寫您的聯絡地址！');
         }
         else if (getEmail().length == 0)
         {
            MyAlert.jsShow('請填寫您的有效Email！');
         }
         //else if (getID().length == 0)
         //{
            //MyAlert.jsShow('請填有效身份證字號！');
         //}
         else
         {
            ret = true;
         }

         return ret;
      }

      public function sendData():void
      {
         // 先檢查是否可送出
         if (canSend)
         {
            canSend = false;
         }
         else
         {
            MyAlert.jsShow('資料傳送中，請耐心等待');
            return;
         }

         //trace('***** Check Data *****');
         //trace('usr =', DEF.usr);
         //trace('id =', DEF.id);
         //trace('birthday =', DEF.birthday);
         //trace('tel =', DEF.tel);
         //trace('addr =', DEF.addr);
         //trace('email =', DEF.email);
         //trace('*********************');

         // 圖片
         //var ba_1:ByteArray = new JPGEncoder(50).encode(bmpData_1);

         // 把byteArray轉成base64的string
         //var b64_1:String = Base64.encodeByteArray(ba_1);

         var urlVar:URLVariables = new URLVariables();
         urlVar.usrName = getName();
         urlVar.tel = getTel();
         urlVar.addr = getAddr();
         urlVar.email = getEmail();
         //urlVar.img_1 = b64_1;

         // 用builder做出來有header的urlRequest
         var urlReq:URLRequest = new URLRequestBuilder(urlVar).build();
         urlReq.url = POST_URL;
         urlReq.method = URLRequestMethod.POST;
         //urlReq.data = urlVar; // 應該是不需要再設一次了

         // 回傳的格式
         ldr = null;
         ldr = new URLLoader();
         ldr.addEventListener(IOErrorEvent.IO_ERROR, onIOErr);
         ldr.addEventListener(Event.COMPLETE, onDataSended);
         ldr.dataFormat = URLLoaderDataFormat.VARIABLES;
         ldr.load(urlReq);
      }

      /**
       * @usage 重填所有表格
       * @usage Clear all the form
       */
      public function clearData():void
      {
         if (tfName) tfName.text = '';

         if (tfTel) tfTel.text = '';

         if (tfAddr) tfTel.text = '';

         //if (tfID) tfID.text = '';

         if (tfEmail) tfEmail.text = '';
      }

      // ------------------ LINE -------------------
      //          這區塊的函式是為了表格的RegExp檢查

      public function getName():String
      {
         return StringUtil.trim(tfName.text);
      }
      public function getTel():String
      {
         return StringUtil.trim(tfTel.text);
      }
      public function getAddr():String
      {
         return StringUtil.trim(tfAddr.text);
      }
      public function getEmail():String
      {
         // regexp
         if (-1 == tfEmail.text.search(/@/))
         {
            return '';
         }
         else
         {
            return tfEmail.text;
         }
      }

      // 身份證
      //public function getID():String
      //{
         //var str:String = tfID.text.replace(/(^[\s　]*)|([\s　]*$)/g, "");
         //if (-1 == str.search(/^[A-Za-z]{1}[0-9]{9}$/) || str == "")
         //{
            //return '';
         //}
         //else
         //{
            //return str;
         //}
      //}

      // 生日
      //public function getBirthday():String { return cbBirthday.value; }

      // ################ Protected ################

      // ################# Private #################

      private function onAdd(e:Event):void
      {
         // characters restriction
         tfTel.restrict = "0-9\\-";
         tfEmail.restrict = "a-z0-9\_\.\\-@";
         //tfID.restrict = "A-Z0-9";

         // set tab index
         textFields = [tfName, tfTel, tfAddr, tfEmail];
         stage.focus = textFields[0]; // set focus to 1st one.
         for (var i:uint = 0; i < textFields.length; ++i)
         {
            var tf:TextField = textFields[i] as TextField;
            tf.tabIndex = i + 1;
            // 讓cursor到最後
            if(i == 0) tf.setSelection(tf.length, tf.length);
         }

         // keyboard input
         stage.addEventListener(KeyboardEvent.KEY_DOWN, onCheckTextField);

         // data
         canSend = true;
      }

      private function onRemove(e:Event):void
      {
         // keyboard input
         stage.removeEventListener(KeyboardEvent.KEY_DOWN, onCheckTextField);

         ////ldr.close();
         if (ldr)
         {
            ldr.removeEventListener(IOErrorEvent.IO_ERROR, onIOErr);
            ldr.removeEventListener(Event.COMPLETE, onDataSended);
            ldr = null;
         }
      }

      // ------------------ LINE -------------------

      private function onDataSended(e:Event):void
      {
         ldr.removeEventListener(Event.COMPLETE, onDataSended);
         canSend = true;
         var param:Object = e.target.data as Object;

         // debug
         //trace('----- onDataSended -----');
         //for (var v:* in param)
         //{
            //trace(v, '=', param[v]);
         //}
         //trace('------------------------');

         // 發出 complete event
         dispatchEvent(new Event('complete'));
      }

      private function onIOErr(e:IOErrorEvent):void
      {
         ldr.removeEventListener(IOErrorEvent.IO_ERROR, onIOErr);
         canSend = true;
         trace('>>> onIOErr <<<');

         // 發出 error event
         dispatchEvent(new Event('error'));
      }

      // ------------------ LINE -------------------

      /**
       * Nomally for "Enter" keyboard event.
       * Implement an Auto Tab between text fields. Doing so will set focus on the next defined text field when the maximum number of characters have been introduced in the previous one. Let’s get going!
       */
      private function onCheckTextField(e:KeyboardEvent):void
      {
         var tf:TextField = stage.focus as TextField;
         var i:int = textFields.indexOf(tf);
         var nexti:int = i + 1 < textFields.length ? i + 1 : 0;
         var previ:int = i - 1 > -1 ? i -1 : textFields.length - 1;

         if (e.keyCode == Keyboard.ENTER)
         {
            sendData();
         }
         else if (e.keyCode == Keyboard.TAB)
         {
            // DO NOTHING, but have to catch
         }
         else if (e.keyCode == Keyboard.BACKSPACE)
         {
            if (tf.length == 0)
            {
               stage.focus = textFields[previ];
            }
         }
         else
         {
            if (tf.length == tf.maxChars)
            {
               stage.focus = textFields[nexti];
            }
         }
      }

      // ------------------ LINE -------------------

   }

}